//数据库构建函数

function localDB(dbName,tableName){
    this.dbName = dbName;
    this.tableName = tableName;
    this.db = null;
}


// 数据库open 方法
localDB.prototype.open = function(callback){
    var _this  = this;
    var request = window.indexedDB.open(_this.dbName,1); 
   
    request.onsuccess = function(event){
        _this.db = request.result;
        callback && callback();
    };

    request.onupgradeneeded = function(event){
       var db = request.result;
       if(!db.objectStoreNames.contains(_this.tableName)){
            db.createObjectStore(_this.tableName,{
                keyPath:'id',
                autoIncrement:true,
            });
       }
    };
    request.onerror = function(err){
        console.log('err',err);
    };
}



// 获取数据库实例
localDB.prototype.getSTore = function(){
    // console.log('this.db',this.db);
    var transaction = this.db.transaction(this.tableName,'readwrite');
   var objStore =  transaction.objectStore(this.tableName);
   return objStore;
}




//获取表中所有数据
localDB.prototype.getALL = function(callback){
    var objectStore = this.getSTore();
    var request = objectStore.openCursor();
    request.onsuccess = function(event){

      
        var cursor = event.target.result;
        if(cursor){
           // console.log('cursor',cursor)
            callback && callback(cursor.value);
            cursor.continue();
        }
    }
}


//获取一条数据
localDB.prototype.get = function(data,callback){
    var objectStore = this.getSTore();
    var request = data.get(id);
    request.onsuccess = function(event){
       // console.log('xxxxxxxxxxxxxxxxxxxx',event.target);
        callback && callback(event.target.result)
    }
}

// 设置一条数据
localDB.prototype.set = function(data,callback){
    var objStore = this.getSTore();
    var request = data.ID ? objStore.put(data) : objStore.add(data);
    // console.log('request',request);
    request.onsuccess = function(event){
        //console.log('xxxxxxxxxxxxxxxxxxxx',event.target);
        callback && callback(event.targrt);
    }
};






